/*
 * @Author: 张久冬
 * @Date: 2021-12-21 22:28:40
 * @
# Description:
 */
import { Module } from 'vuex'
import type { IRootState } from '../type'
import { IloginState } from './type'
import LocalCache from '@/utils/cache'
import {
  accountLoginRequest,
  requestUserInfoByid,
  requestUserMenusByRoleid
} from '../../service/login/login'
import { mapMenusToRouters } from '@/utils/map-menus'
import router from '@/router'
import type { IaccountType } from '../../service/login/type'

const loginModule: Module<IloginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: []
    }
  },
  getters: {},
  actions: {
    async accountLoginAction({ commit }, payload: IaccountType) {
      // 登陆验证
      const logoinResult = await accountLoginRequest(payload)
      const { id, token } = logoinResult.data
      // 将用户的token保存在vuex内,本地缓存
      commit('changeToken', token)
      LocalCache.setCache('token', token)

      // 获取用户信息保存在vuex内,本地缓存
      const userInfoResult = await requestUserInfoByid(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      console.log('userInfo', userInfo)
      LocalCache.setCache('userInfo', userInfo)
      // 获取用户角色
      const userMenusResult = await requestUserMenusByRoleid(userInfo.role.id)
      const userMenus = userMenusResult.data
      console.log('role', userMenus)
      commit('changeUserMenus', userMenus)
      LocalCache.setCache('userMenus', userMenus)
      // 跳转到首页
      router.push('/main/')
    },
    // 如果用户已经登陆，但是用户手动刷新了网页导致vuex中数据丢失，手动导入数据
    loadLocalLogin({ commit }) {
      const token = LocalCache.getCache('token')
      if (token) {
        commit('changeToken', token)
      }
      const userInfo = LocalCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = LocalCache.getCache('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      // 此处根据用户权限动态添加路由
      const routes = mapMenusToRouters(userMenus)
      // console.log('获取用户当前权限路由', routes)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
    }
  }
}
export default loginModule
